package com.example.administrator.mvvm.module.login;

import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;
import android.databinding.ObservableField;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Toast;

import com.example.administrator.mvvm.model.user.UserRepository;

public class LoginViewModel extends AndroidViewModel {
    //上下文
    private Application application;
    //LiveData是一个可被观察的数据持有者，他能感知组件的生命周期，用来关联View与ViewModel的
    private MutableLiveData<Boolean> loginLiveData = new MutableLiveData<>();
    //model数据源
    private UserRepository userRepository;
    //数据字段与控件绑定
    public ObservableField<String> userName = new ObservableField<>();
    public ObservableField<String> password = new ObservableField<>();

    public LoginViewModel(@NonNull Application application) {
        super(application);
        this.application = application;
        this.userRepository = new UserRepository(application);
    }

    /**
     * 登录
     */
    public void login(View view) {
        if (TextUtils.isEmpty(userName.get())) {
            Toast.makeText(application, "用户名不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(password.get())) {
            Toast.makeText(application, "密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        boolean succ = userRepository.login(userName.get(), password.get());
        loginLiveData.setValue(succ);
    }

    /**
     * 观察用户名输入框的输入事件
     *
     * @return
     */
    public TextWatcher getUsernameUpdate() {
        return new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        };
    }

    /**
     * 观察密码输入框的输入事件
     *
     * @return
     */
    public TextWatcher getPasswordUpdate() {
        return new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        };
    }

    public MutableLiveData<Boolean> getLoginLiveData() {
        return loginLiveData;
    }
}
